/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package org.aroundme.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aroundme.model.ApplicationSecurityManager;
import org.aroundme.model.XMLRequestParser;
import org.aroundme.utility.Constants;
import org.jdom.JDOMException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
 * This class intercepts all incoming HTTP requests and for doing
 * a security check by using the appropriate classes.
 */
public class HttpRequestInterceptor extends HandlerInterceptorAdapter{
	private static Log log = LogFactory.getLog(HttpRequestInterceptor.class);
	private ApplicationSecurityManager securityManager = null;
	private XMLRequestParser xmlHandler = null;
	private ResponseController responseController = null;
	
	/**
	 * catches all requests and analyzes the authentication data
	 * returns true if the authentication succeeded, false otherwise
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
		responseController.setResponse(response);
		String errorMsg = null;
		//retrieving the data
		String xmlString = null;
		try {
			xmlString = readRequest(request);
			log.info("Incoming xml request: " + xmlString);
			xmlHandler.loadDocumentModel(xmlString);
			
			String currUser = xmlHandler.getUserLoginName();
			String password = xmlHandler.getEncryptedPassword();
			boolean loginValid = securityManager.checkLogin(currUser, password);
			if(!loginValid)
				errorMsg = "Authentication failure!";
		} catch (IOException e) {
			errorMsg = e.getMessage();
		} catch (JDOMException e) {
			errorMsg = e.getMessage();
		} catch (Exception e) {
			if(e.getMessage().equals("empty request")){
				//server has probably been accessed through a web-browser
				errorMsg = "Invalid HTTP request";
				printHTML(response);
				return false; //don't return anything in this case
			}else
				errorMsg = e.getMessage();
		}
		
		if(errorMsg!=null){
			responseController.sendAlert(Constants.ALERT_ERROR, errorMsg);
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * trasformes the bytes of the request to a string
	 * @param request HttpServletRequest object
	 * @return String containing the byte[] array
	 * @throws Exception 
	 */
	private String readRequest(HttpServletRequest request) throws Exception{
		InputStream in;
		byte[] data = null;
		try {
			in = request.getInputStream();
			data = new byte[request.getContentLength()];
			in.read(data);
		} catch (Exception e) {
			throw new Exception("empty request");
		}
		
		return new String(data);
	}
	
	private void printHTML(HttpServletResponse response){
		String html = "" +
				"<html>" +
				"<head></head>" +
				"<body>" +
				"<h1>Around(J2)ME Server</h1>" +
				"<h2>Authentication Service</h2>" +
				"<p>" +
				"It seems as if you tried to access the Around(J2)ME Server through a web browser, however the " +
				"server accepts only requests from the appropriate Around(J2)ME mobile clients." +
				"</p>" +
				"<p>" +
				"<h1>Server Details:</h1>" +
				"<table border=\"0\">" +
				"<colgroup>" +
				"	<col style=\"font-weight:bold;\"/>" +
				"</colgroup>" +
				"<tr>" +
				"	<td>Version:</td>" +
				"	<td>" + Constants.SERVER_VERSION +
				"</tr>" +
				"</table>" +
				"</p>" +
				"</body>" +
				"</html>";
		try {
			response.getWriter().println(html);
		} catch (IOException e) {
			log.error(e.getStackTrace());
		}
	}
	
	/*
	 * Getters and Setters
	 */
	
	public ApplicationSecurityManager getSecurityManager() {
		return securityManager;
	}

	public void setSecurityManager(ApplicationSecurityManager securityManager) {
		this.securityManager = securityManager;
	}

	public XMLRequestParser getXmlHandler() {
		return xmlHandler;
	}

	public void setXmlHandler(XMLRequestParser xmlHandler) {
		this.xmlHandler = xmlHandler;
	}

	public ResponseController getResponseController() {
		return responseController;
	}

	public void setResponseController(ResponseController responseController) {
		this.responseController = responseController;
	}
	
}
